package com.local.videoplayer.activity;

import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.local.videoplayer.R;
import com.local.videoplayer.adapter.FolderAdapter;
import com.local.videoplayer.bean.FolderBean;
import com.local.videoplayer.bean.VideoBean;
import com.local.videoplayer.utils.LogUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ccx on 17/3/30.
 */

public class MainActivity extends BaseActivity
{

	private SwipeRefreshLayout mPullRefreshView;
	private RecyclerView mVideoRecycleView;
	private FolderAdapter mAdapter;
	private View mProgressView;
	private Thread mGeteDataThread;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		getData();
	}

	private void getData()
	{
		mGeteDataThread = new Thread()
		{
			@Override
			public void run()
			{
				super.run();
				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						try
						{
							mProgressView.setVisibility(View.VISIBLE);
						} catch (Exception e)
						{
							e.printStackTrace();
						}

					}
				});

				Cursor cursor = getContentResolver().query(
				        MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null,
				        null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
				ArrayList<VideoBean> videoList = new ArrayList();

				if (cursor != null)
				{
					while (cursor.moveToNext())
					{
						VideoBean bean = new VideoBean();
						bean.videoName = cursor
						        .getString(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.TITLE));
						bean.duration = cursor
						        .getLong(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.DURATION));
						String mimeType = cursor
						        .getString(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.MIME_TYPE));

						bean.videoPath = cursor
						        .getString(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.DATA));
						if (!TextUtils.isEmpty(bean.videoPath))
						{
							String[] paths = bean.videoPath.split("/");
							bean.videoName = paths[paths.length - 1];
						}
						if (!TextUtils.isEmpty(mimeType)
						        && !TextUtils.isEmpty(MimeTypeMap.getSingleton()
						                .getExtensionFromMimeType(
						                        bean.mimeType)))
						{
							bean.videoName = bean.videoName + "."
							        + MimeTypeMap.getSingleton()
							                .getExtensionFromMimeType(
							                        bean.mimeType);
						}
						bean.size = cursor.getLong(cursor.getColumnIndexOrThrow(
						        MediaStore.Video.Media.SIZE));
						bean.videoImg = cursor
						        .getString(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.ALBUM));
						// bean.bitmap = getVideoThumb(bean.videoPath);
						bean.updateTime = cursor
						        .getLong(cursor.getColumnIndexOrThrow(
						                MediaStore.Video.Media.DATE_MODIFIED));
						videoList.add(bean);

						LogUtil.e("ccx VIDEO", bean.toString());
					}
					cursor.close();
				}
				final Map<String, FolderBean> folderBeanMap = new HashMap<>();
				for (VideoBean videoBean : videoList)
				{
					String path = videoBean.videoPath.substring(0,
					        videoBean.videoPath.length()
					                - videoBean.videoName.length());
					FolderBean bean = folderBeanMap.get(path);
					if (bean == null)
					{
						bean = new FolderBean();
						folderBeanMap.put(path, bean);
						bean.path = path;
						String[] paths = bean.path.split("/");
						bean.name = paths[paths.length - 1];
					}

					bean.videos.add(videoBean);
				}

				runOnUiThread(new Runnable()
				{
					@Override
					public void run()
					{
						try
						{
							mAdapter.setNewData(
							        new ArrayList<>(folderBeanMap.values()));
							mProgressView.setVisibility(View.GONE);
							mVideoRecycleView.setVisibility(View.VISIBLE);
							mPullRefreshView.setRefreshing(false);
						} catch (Exception e)
						{

						}

					}
				});

			}
		};

		mGeteDataThread.start();
	}

	private void initView()
	{
		mPullRefreshView = findViewByIdExt(R.id.swipeLayout);
		mPullRefreshView
		        .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
		        {
			        @Override
			        public void onRefresh()
			        {
				        getData();
			        }
		        });

		mVideoRecycleView = findViewByIdExt(R.id.video_rv_list);
		mProgressView = findViewById(R.id.progressBar);
		mProgressView.setVisibility(View.VISIBLE);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		mVideoRecycleView.setLayoutManager(layoutManager);
		mAdapter = new FolderAdapter();
		mVideoRecycleView.setAdapter(mAdapter);
		mAdapter.setOnItemClickListener(
		        new BaseQuickAdapter.OnItemClickListener()
		        {
			        @Override
			        public void onItemClick(BaseQuickAdapter adapter, View view,
			                int position)
			        {
				        Bundle bundle = new Bundle();
				        bundle.putParcelable("DATA",
				                (Parcelable) adapter.getItem(position));
				        goToOthers(VideoListActivity.class, bundle);
			        }
		        });
		findViewById(R.id.ll_lock_folder).setOnClickListener(this);
		findViewById(R.id.ll_refresh).setOnClickListener(this);
		findViewById(R.id.ll_menu).setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		super.onClick(v);
		switch (v.getId())
		{
			case R.id.ll_refresh:
				mPullRefreshView.setRefreshing(true);
				getData();
				break;
			case R.id.ll_lock_folder:
				goToOthers(LockViewActivity.class);
				break;
		}
	}
}
